Tuesday, October 1, 2024

Basic plot custiomization

Basic Plot Customization

The customization is necessary to position the plot legend, create labels, titles and so on. In matplotlib you can customize the appearance of titles, labels, and legends. The title is created using plt.title() function.
plt.title("Squared Numbers", fontsize = 20)
The previous code defines the title of the plot "Squared Numbers" and customized by setting the fontsize to 20. The xlabel and ylabel are created and customized using plt.xlabel() and plt.ylabel() functions.
plt.xlabel("X-axis", color = 'green')
plt.ylabel("Y-axis", color = 'red', fotnstyle='italic')
In the previous code block we have defined xlabel "X-axis" and the ylabel "Y-axis". These labels are customized by setting the xlabel font color to green and ylabel fontcolor to red. The ylable fontstlye is set to italic. The legend is defined using the plt.legend() function. The example of plt.legend() function customization is shown below.
plt.legend(["y = x^2"], fontsize=20)
The previous code block will define the plot legend and set the fontsize of the legend label to 20.

How to customize titles ?

The title customization is performed using the plt.title() function and adding the parameters inside the title function to modify the font size, color, weight, and alignment.
All the aforementioned customizations will be performed on the sine plot.

Example - The sine plot

> In this example we will plot the sine wave using the matplotlib.pyplot.plot() or plt.plot() function. The example consist of the following steps:
  • Importing required libraries
  • defining the dataset
  • defining and showing the plot

Importing required libraries

In this example we will need numpy library to generate the dataset and matplotlib.pyplot library to create the sine wave.
import numpy as np 
import matplotlib.pyplot as plt 
The first library is the NumPy (nuerical python) which is the powerful library for performing numerical computation in Python programming language. The NumPy provides support for large multi-dimensional arrays and matrice,s along with collection of mathematical functions to operate on these arrays efficiently. The np is an alias of the numpy function which makes it easier to use throughout the code. Instead of typing the numpy, you can use the shorter np, which is the convention in most Python projects. The numpy In this example we will need the numpy library to generate the x-coordinates using np.linspace() function and y-coordinates using the np.sin() function.\newline You probably know that matplotlib is the comprehensive Python library used for creating static, animated, and interactive visualization. The matplotlib is used for creating the plots, graphs and charts. The pyplot is a submpdule of Matplotlib that provides a collection of functions to create and manipulate plots in a MATLAB-like way. The pyplot is very useful since it offers high-level functions such as plot(), xlabel(), title(), and legend() using which it is very easy to create the plot. The plt is the alias of the pyplot submodule and using plt you dont have to type matplotlib.pyplot every time you want to use one of its functions. In this example we will use plt.figure(), plt.plot(), plt.title(), and plt.show() function.

Defining the dataset

This step is practically self-explanatory since we have to generate the dataset that will be plotted using the matplotlib library. In this example we want to generate and plot the sine wave. To plot the sine wave we have to define the x and y coordinates of the sine wave.
x = np.linspace(0,10,1000)
y = np.sin(x)
The x-coordinates are generate using the numpy linspace function. The function in this case will generate the array from 0 to 10 (including 10) with total of 1000 values. So the step between two values is equal to 0.01 (divide 10 by 1000). The y-coordinates are generated using the np.sin() function applied on the x-coordinates (previously created array using np.linspace() function).

Defining and showing plot

Now that libraries are imported and the dataset is created we can define plot and generate it using plt.show() function. In other words to define the plot we need to define the figure (empty figure) set the figure size, define the plt.plot(), and set the title of the plot (the tile is "Sine Wave").
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.title("Sine Wave")
plt.show()
The empty figure is created using plt.figure() the figure size is defined using the figsize parameter and set to 12 by 8 inches. The sine wave is defined and generated using the x and y coordinates generated previously as the parameters of the plt.plot() function. The title "Sine Wave" is created using the plt.title(). The sine wave will be displayed (shown) using the plt.show() function. \newline The entire code created in this example is shown below.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.show()
When the previous code is executed the generated plot is shown in Figure 1.
2024-10-01T22:26:01.504018 image/svg+xml Matplotlib v3.8.0, https://matplotlib.org/
Figure 1 - Sine Wave

How to customize of plot Title ?

> This example is the extension of the "Sine Wave" example particularly the title. The default fontsize of the plt.title() in Matplotlib is 12. The default value of fontweight parameter is normal, the default value of the color parameter is black, and the loc which stands for position the default value is center. In this example we want to set the fontsize to 18, the fontweight to 'bold', color to 'darkblue', and the loc to 'center'. The customization of the plt.title() function is shown below.
plt.title("Sine Wave", fontsize=18, fontweight='bold', color='darkblue', loc='center')
The entire code with modifications of the plt.title() is shown below.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave", fontsize=18, fontweight='bold', color='darkblue', loc='center')
plt.show()
The result of previous code block is shown in Figure 2.
2024-10-01T22:29:43.812391 image/svg+xml Matplotlib v3.8.0, https://matplotlib.org/
Figure 2 - Title customization on the sine wave plot

Customizing x-labels and y-labels

In this example we want to create the x and ylabel and make some customization. To create the x and y labels we have to use the plt.xlabel() and plt.ylabel() function. The x label in this example will be "Time (Seconds)" and the y label will be "Amplitude". The x and y labels definition is shown below.
plt.xlabel('Time (seconds)')
plt.ylabel('Amplitude')
The entire example "Sine Wave" with added x and y labels are shown below.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave", fontsize=18, fontweight='bold', color='darkblue', loc='center')
plt.xlabel('Time (seconds)")
plt.ylabel('Amplitude')
plt.show()
The result of previous code block is shown in the Figure 3.
2024-10-01T22:45:02.909861 image/svg+xml Matplotlib v3.8.0, https://matplotlib.org/
Figure 3 - Sine wave plot with customized x and y-axis labels
To customize the xlabel and ylabel is to set for both labels the fontsize of 14. The x-axis label will be in italic format so the fontstyle for xlabel is set to italc. The y-axis label will be bold so the fontweight will be set to bold. The fontcolor or simply color for xlabel will be "purple" and for y label the color will be green.
plt.xlable('Time (seconds)', fontsize=14, fontstyle = 'italic', color = 'purple')
plt.ylabel('Amplitude', fontsize=14, fontweight = 'bold', color = 'green')
The entire code with customization is shown below.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave", fontsize=18, fontweight='bold', color='darkblue', loc='center')
plt.xlabel('Time (seconds)', fontizse = 14, fontstyle='italic', color = 'purple')
plt.ylabel('Amplitude', fontizse=14, fontweight = 'bold', color = 'green')
plt.show()
The plot generated from the previous code is shown in Figure 4.
Figure 4 - Sine wave plot with customized legend.

Customizing legends

To customize legends generally in matplotlib you will have to use the plt.legend() function and specify its location, font size, shadow, background color, and more. To define with default style the legend of the plot simply type the plt.legned(). However it is crucial to modify each plot function in the code. To define the legend with default values simply type the following code.
plt.legend()
If we use plt.legelnd() only without labeling the plot figure in the ifnal form will not contain the legend. So for this example we have to modify the plt.plot() function. In this function after definition of hte plt.plot() and x and y lists the parameter label = "Sine Wave" will be added.
plt.plot(x,y, label = 'Sine Wave')
            
To customize the legends,5 you use the plt.legend() function and specify its location,fontize, shadow, background color, and more. In this case we will position the legend to the upper right corner of the plot, set the fontsize to 12, add the shadow (shadow = True), round the edges of the legend box by setting the fancybox to True, and finally set the facecolor to 'lightgray'.
plt.legend(loc = 'upper right', fontsize=12, shadow = True, fancybox = True, facecolor = 'lightgray')
The entire code with modified plt legend is shown below.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave", fontsize=18, fontweight='bold', color='darkblue', loc='center')
plt.xlabel('Time (seconds)', fontizse = 14, fontstyle='italic', color = 'purple')
plt.ylabel('Amplitude', fontizse=14, fontweight = 'bold', color = 'green')
plt.legend(loc = 'upper right', fontsize=12, shadow = True, fancybox = True, facecolor = 'lightgray')
plt.show()
The result of the previous code is shown in Figure 5.
2024-10-01T22:57:53.484624 image/svg+xml Matplotlib v3.8.0, https://matplotlib.org/
Figure 4 - The sine wave plot with customized legend.

No comments:

Post a Comment